﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FCS
{
    #region HeadTailHelper<T>

    sealed class HeadTailHelper<T> : FunList<T>
    {
        public T Head { get; private set; }
        public bool HasHead { get; private set; }
        private IFunList<T> List { get; set; }
        private IEnumerator<T> ListEnumerator { get; set; }
        private static readonly List<T> EmptyList = new List<T>();
        private bool _Enumerated;

        public HeadTailHelper(IFunList<T> list)
        {
            List = list;
            ListEnumerator = List.GetEnumerator();

            HasHead = ListEnumerator.MoveNext();
            Head = HasHead ? ListEnumerator.Current : default(T);
            _Enumerated = false;
        }

        #region IEnumerable<T> Members

        public override IEnumerator<T> GetEnumerator()
        {
            if (_Enumerated)
            {
                ListEnumerator = List.GetEnumerator();

                if (!ListEnumerator.MoveNext())
                {
                    return EmptyList.GetEnumerator();
                }
            }
            _Enumerated = true;

            return ListEnumerator;
        }

        #endregion
    }

    #endregion
}
